<?php
/**
 * Description of ActionGenerator
 *
 * @author BloumGenerator
 */
class ActionGenerator {
    
    private $tableMeta;
    private $parentTbMeta;
    private $templateAction;
    private $attPK;
    private $params;

    function __construct($tableMeta, $params) {
        $this->tableMeta = $tableMeta;
        $this->params = $params;
        $this->parentTbMeta = null;

        if(!file_exists(Constantes::$TEMPLATES_ACTION_DIR."Action.bloum"))
            throw new Exception ("Template Action Not Found!!!");

        $this->templateAction = file_get_contents(Constantes::$TEMPLATES_ACTION_DIR."Action.bloum");
        $this->searchPK();
        $this->searchParent();

    }

    public function searchPK(){
        $numExt = 0;
        foreach ($this->tableMeta->getFKReferences() as $fk) {
            if($fk->isExtends()){
                $numExt++;
                $this->parentTbMeta = $fk->getTableReference();
            }
        }
        if($numExt > 1){
            throw new Exception("Erro, Herança Multipla Não Suportado!!!");
        }
    }

    public function searchParent(){
        foreach ($this->tableMeta->getAttributes() as $att) {
            if($att->isPrimaryKey()){
                $this->attPK[$att->getName()] = $att;
            }
        }
    }
    
    public function generate(){
        $this->templateAction = str_replace(Constantes::$TPL_BEAN_NAME_UPPER, ucfirst($this->tableMeta->getName()), $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_BEAN_NAME_LOWER, lcfirst($this->tableMeta->getName()), $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_BEAN_NAME_TO_UPPER, strtoupper($this->tableMeta->getName()), $this->templateAction);
        
        $this->generatePkValues();
        $this->generateListParam();
        $this->generateFkValues();
        
        return $this->templateAction;
    }
    
    public function generatePkValues(){

        $tableName = $this->tableMeta->getName();
        
        $pkIfTest = "";
        $pkList = "";
        $pkUrlParam = "";

        $attrsKeys = array_keys($this->attPK);

        for ($i = 0; $i < count($attrsKeys); $i++) {
            $att = $this->attPK[$attrsKeys[$i]];
            $name = $att->getName();
            
            $pkList .= "$".$name;
            $pkIfTest .= " !isset($".$name.") || $".$name." <= 0 ";
            $pkUrlParam .= $name."='.$".$tableName."Bean->get".ucfirst($name)."()";
            
            if($i < ( count($this->attPK)-1 )){
                $pkList .= ", ";
                $pkIfTest .= "\n\t\t\t && ";
                $pkUrlParam .= ".'&";
            }
        }

        $this->templateAction = str_replace(Constantes::$TPL_ACTION_PK_IF_TEST, $pkIfTest, $this->templateAction);        
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_PK_LIST, $pkList, $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_PK_URL_PARAM, $pkUrlParam, $this->templateAction);
    }
    
    public function generateListParam(){
        $attrs = $this->tableMeta->getAttributes();

        if($this->parentTbMeta != null && count($this->parentTbMeta->getAttributes()) > 0)
            $attrs = array_merge ($attrs,$this->parentTbMeta->getAttributes());

        $attrsKeys = array_keys($attrs);
        $tableName = $this->tableMeta->getName();
        $listParam = "";
        $listParamInit = "";

        for ($i = 0; $i < count($attrsKeys); $i++) {
            $name = $attrsKeys[$i];

            if(!$attrs[$name]->isPrimaryKey() && $attrs[$name]->isImportant()){
                
                if(strlen($listParam) > 0)
                    $listParam .= ",";
                
                $listParam .= "$$name";

                $type = $attrs[$name]->getType();
                $default = $attrs[$name]->getDefault();

                $value = '""';
                if(Util::isTypeNumeric($type)){
                    $value = "-1";
                    if(strlen($default))
                        $value = $default;

                }else{
                    $value = "\"\"";
                    
                }

                $listParamInit .= ",$".$name." = ".$value;                
                
            }

        }

        $this->templateAction = str_replace(Constantes::$TPL_LIST_PARAM_INIT, $listParamInit, $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_LIST_PARAM, $listParam, $this->templateAction);        
        $this->templateAction = str_replace(",,", ",", $this->templateAction); #gambiarra        
    }
    
    public function generateFkValues(){
        $tableName = $this->tableMeta->getName();
        
        $fksCombo = "";
        $fksBuscarSalvar = "";
        $fksSetSalvar = ""; 
        $fksService = "";
        $fksInitService = "";
        $fksOutput = "";

        $fksMeta = $this->tableMeta->getFKReferences();

        if($this->parentTbMeta != null && count($this->parentTbMeta->getFKReferences()) > 0)
            $fksMeta = array_merge($fksMeta,$this->parentTbMeta->getFKReferences());

        $fksKeys = array_keys($fksMeta);

        for ($i = 0; $i < count($fksKeys); $i++) {
            $fk = $fksMeta[$fksKeys[$i]];
            $name = $fk->getTableReference()->getName();
            
            $fksService .= "private $".$name."Service;\n\t";
            $fksInitService .= "\$this->".$name."Service = new ".ucfirst($name)."Service();\n\t\t";
            $fksSetSalvar .= "$".$tableName."Bean->set".ucfirst($name)."($".$name."Bean);\n\t\t\t";
            $comboDisplay = "";
            
            if(strcmp($fk->getTypeForm(), Constantes::$TYPE_FORM_COMBO) == 0){

                $fksBuscarSalvar .= "$".$name."Bean = \$this->".$name."Service->buscarPorID(parent::getValueInput('".$name."ID'));\n\t\t\t";
                $fksCombo .= "parent::setValueOutput('".$name."s', Util::arrayCombo(\$this->".$name."Service->listar(), '".$name."ID', ':comboDisplay'));\n\t\t";

                foreach ($fk->getTableReference()->getAttributes() as $attFk) {
                    if($attFk->isComboDisplay()){
                        $comboDisplay = $attFk->getName();
                        break;
                    }
                }
            
            }else if(strcmp($fk->getTypeForm(), Constantes::$TYPE_FORM_HIDDEN_ID) == 0){
                $fksBuscarSalvar .= "$".$name."Bean = \$this->".$name."Service->buscarPorID(parent::getValueInput('".$name."ID'));\n\t\t\t";
            }else if(strcmp($fk->getTypeForm(), Constantes::$TYPE_FORM_INCLUDE) == 0){
                $fksBuscarSalvar .= "$".$name."Bean = parent::getObjectInput('".ucfirst($name)."Bean', '".$name."_');\n\t\t\t";
                $fksOutput .= "parent::setObjectOutput($".$tableName."Bean->get".ucfirst($name)."(), '".$name."_');\n\t\t\t";
            }else{
                $fksBuscarSalvar .= "#recuperar objeto: ".$name."Bean\n\t\t\t";                
            }
            
            $fksCombo = str_replace(":comboDisplay", $comboDisplay, $fksCombo);
        }

        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_SERVICE, $fksService, $this->templateAction);        
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_INIT_SERVICE, $fksInitService, $this->templateAction);        
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_COMBO, $fksCombo, $this->templateAction);        
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_BUSCAR_SALVAR, $fksBuscarSalvar, $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_SET_SALVAR, $fksSetSalvar, $this->templateAction);
        $this->templateAction = str_replace(Constantes::$TPL_ACTION_FKS_OUTPUT, $fksOutput, $this->templateAction);
    }

    public function generateFile($generate = true){

        if($generate)
            $this->generate();

        $dirModel = "temp_gen/".$this->params[Constantes::$PARAM_PROJECT_NAME]."/action/";

        if(!file_exists($dirModel))
            mkdir ($dirModel, 0755,true);

        $fp = fopen($dirModel.ucfirst($this->tableMeta->getName())."Action.class.php", "w+");
        fwrite($fp, $this->templateAction);
        fclose($fp);
    }

}

?>
